package cn.aoyu.test; /**
 * @ClassName: TestConcurrentRequest
 * @Auther: xww
 * @Date: 2019/5/9 0009 16:13
 * @Description:
 */

import cn.aoyu.test.service.test.TestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 对项目进行压测
 * 目标：编写一段代码，模拟并发请求为20，且总的请求数为1000，当1000个请求完成后，打印“请求完成”
 */
public class ConcurrentRequestTestDemo {

	private static final Logger log = LoggerFactory.getLogger(ConcurrentRequestTestDemo.class);

	private static ApplicationContext context = new ClassPathXmlApplicationContext("spring-mybatis.xml");

	// 总的请求个数
	public static final int requestTotal = 1;

	// 同一时刻最大的并发线程的个数
	public static final int concurrentThreadNum = 1;

	public static void main(String[] args) throws InterruptedException {
		ExecutorService executorService = Executors.newCachedThreadPool();
		CountDownLatch countDownLatch = new CountDownLatch(requestTotal);
		Semaphore semaphore = new Semaphore(concurrentThreadNum);
		for (int i = 0; i < requestTotal; i++) {
			executorService.execute(() -> {
				try {
					semaphore.acquire();
					applicationTest();
					semaphore.release();
				} catch (InterruptedException e) {
					log.error("exception", e);
				}
				countDownLatch.countDown();
			});
		}
		countDownLatch.await();
		executorService.shutdown();
		log.info("请求完成");
	}

	private static void applicationTest() {
		String userId = UUID.randomUUID().toString();
		TestService testService = (TestService) context.getBean("testServiceImpl");
		testService.redisTest(userId, 1);
	}
}
